//
//  NSData+Byte.m
//  BJH
//
//  Created by xtjun on 2023/10/14.
//

#import "NSData+Byte.h"

@implementation NSData (Byte)


+ (NSData *)dataByteArrayFromValue:(int)value withByteCount:(int)byteCount {
    NSMutableData *data = [NSMutableData dataWithCapacity:byteCount];
    
    if (IS_LITTLE_ENDIAN) {
        for (int i = 0; i < byteCount; i++) {
            uint8_t byte = (value >> (8 * i)) & 0xFF;
            [data appendBytes:&byte length:1];
        }
    } else {
        for (int i = (byteCount - 1); i >= 0; i--) {
            uint8_t byte = (value >> (8 * i)) & 0xFF;
            [data appendBytes:&byte length:1];
        }
    }
    
    return data;
}


- (int32_t)readValueAtRange:(NSRange)range {
    int32_t value = 0;
    
    if (IS_LITTLE_ENDIAN) {
        for (NSUInteger i = range.location + range.length - 1; i >= range.location; i--) {
            uint8_t byte;
            [self getBytes:&byte range:NSMakeRange(i, 1)];
            value = (value << 8) | byte;
        }
    } else {
        for (NSUInteger i = range.location; i < range.location + range.length; i++) {
            uint8_t byte;
            [self getBytes:&byte range:NSMakeRange(i, 1)];
            value = (value << 8) | byte;
        }
    }
    
    return value;
}
 
@end
